<template>
  <div class="merchant-register">
    <div class="register-container">
      <h2 class="title">商家入驻</h2>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="register-form"
      >
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商家名称" />
        </el-form-item>

        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>

        <el-form-item label="商家地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入商家地址" />
        </el-form-item>

        <el-form-item label="营业执照" prop="licenseUrl">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleLicenseSuccess"
            :on-error="handleLicenseError"
            :before-upload="beforeLicenseUpload"
            :on-progress="handleProgress"
            :limit="1"
            :file-list="fileList"
            list-type="picture-card"
            name="file"
            :data="uploadData"
            :show-file-list="true"
            :auto-upload="true"
            accept=".jpg,.jpeg,.png"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                请上传清晰的营业执照照片，支持jpg/png格式，大小不超过2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="商家简介" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商家简介"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交申请</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { registerMerchant } from '@/api/merchant'
import axios from 'axios'

const router = useRouter()
const formRef = ref(null)
const fileList = ref([])
const uploadUrl = 'http://localhost:8080/api/upload'
const uploadHeaders = {
  'Content-Type': 'multipart/form-data'
}
const uploadData = {
  type: 'license'
}

const form = reactive({
  name: '',
  contact: '',
  phone: '',
  email: '',
  address: '',
  licenseUrl: '',
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入商家名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入商家地址', trigger: 'blur' }
  ],
  licenseUrl: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商家简介', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

const handleLicenseSuccess = (response, file) => {
  console.log('Upload success response:', response)
  console.log('Upload success file:', file)
  
  if (response.code === 200) {
    form.licenseUrl = response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleLicenseError = (error, file) => {
  console.error('Upload error:', error)
  console.error('Upload error file:', file)
  ElMessage.error('上传失败，请重试')
}

const handleProgress = (event, file) => {
  console.log('Upload progress:', event)
  console.log('Upload progress file:', file)
}

const beforeLicenseUpload = (file) => {
  console.log('Before upload file:', file)
  
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传图片大小不能超过 10MB!')
    return false
  }
  return true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    const response = await registerMerchant({
      name: form.name,
      contact: form.contact,
      phone: form.phone,
      email: form.email,
      address: form.address,
      licenseUrl: form.licenseUrl,
      description: form.description
    })
    ElMessage.success(response)
    router.push('/')
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data)
    } else {
      ElMessage.error('提交失败，请稍后重试')
    }
    console.error('表单提交失败:', error)
  }
}

const goBack = () => {
  router.back()
}
</script>

<style scoped>
.merchant-register {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 40px 0;
}

.register-container {
  max-width: 800px;
  margin: 0 auto;
  background-color: #fff;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 40px;
  color: #333;
  font-size: 24px;
}

.register-form {
  max-width: 600px;
  margin: 0 auto;
}

.el-upload__tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

.el-button {
  margin-right: 20px;
}

.upload-demo {
  width: 100%;
}

:deep(.el-upload--picture-card) {
  width: 148px;
  height: 148px;
  line-height: 148px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 148px;
  height: 148px;
}
</style> 